package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Paper;

import core.PgSQL;
import core.View;

public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static PgSQL db = PgSQL.getInstance();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LinkedList<Paper> paper_list = new LinkedList<Paper>();
		LinkedList<String> paper_author = new LinkedList<String>();

		ResultSet rs = db.query("SELECT p.*,u.username FROM qz_paper p LEFT JOIN qz_user u ON u.uid=p.authorid ORDER BY p.pid DESC LIMIT 10");
		try{
			while(rs.next()){
				paper_list.add(Paper.fromDatabase(rs));
				paper_author.add(rs.getString(7));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		request.setAttribute("paper_list[]", paper_list.toArray(new Paper[0]));
		request.setAttribute("paper_author[]", paper_author.toArray(new String[0]));

		View.show(request, response, "index");
	}
}
